<?php


namespace app\api\controller;


use app\BaseController;
use app\common\model\User;
use thans\jwt\facade\JWTAuth;
use think\helper\Str;
use think\Validate;

class Login extends BaseController
{
    /**
     * code登录
     * 通过 openid 进行登录
     */
    public function login()
    {
        $param    = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'code|code' => 'require'
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $wechat = new \Wechat();
        $res    = $wechat->getWechatOpenid($param['code']);
        $user = User::where('openid', $res['openid'])->find();
        if (!$user) {
            //创建用户
            $user = User::create([
                'openid'   => $res['openid'],
                'unionid'  => empty($res['unionid']) ? '' : $res['unionid'],
                'nickname' => 'U_' . Str::random(4),
                'avatar'   => 'https://douxiangtuan-1312696603.cos.ap-shanghai.myqcloud.com/default.jpeg'
            ]);
        }else{
            if(!$user->unionid && $res['unionid']){
                $user->unionid = $res['unionid'];
                $user->save();
            }
        }

        $user->token = JWTAuth::builder(['uid' => $user['id']]);
        //禁用前端授权弹窗
        $user->is_updated = 1;
        //session_key存入缓存,在获取用手机号时使用
        cache('session_key' . $user->id, $res['session_key']);
        return success($user);
    }


}